package com.wzy.shirowebdemo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

    @RequestMapping({"/", "/index"})
    public String test(Model model) {
        model.addAttribute("name", "测试Thymeleaf");
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);
            subject.getSession().setAttribute("loginUser",subject.getPrincipal());
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不存在");
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg","密码不正确");
        }catch (Exception e) {
            model.addAttribute("msg","异常"+e.getMessage());
        }
        return "login";
    }
}
